import java.util.Stack;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/5/15
 * Time:11:26
 **/
public class Main {
    /**
     * 每日一题-合法括号序列判断
     *
     * @param A 括号字符串
     * @param n 字符串长度
     * @return 返回是否合法
     */
    public boolean chkParenthesis(String A, int n) {
        // write code here
        if (n % 2 != 0) {//若为奇数，说明不合法
            return false;
        }
        Stack<Character> stack = new Stack<>();
        for (char ch : A.toCharArray()
        ) {
            if (ch == '(') {
                stack.push(ch);
            } else if (ch == ')') {
                //右括号之前无左括号
                if (stack.isEmpty()) {
                    return false;
                } else if (stack.peek() == '(') {
                    stack.pop();//栈顶元素为（，则出栈，匹配好一组括号
                }
            } else {
                return false;
            }
        }
        return stack.isEmpty();
    }
}
